package com.sushe.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BedAssignmentDao {

    private static final String url="jdbc:mysql://localhost:3306/sushe";
    private static final String username="root";
    private static final String password="123456";


    public  String selectByBuildingId(Integer buildingId) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String sql="select name from dorm_building where id=?";
        Connection connection= DriverManager.getConnection(url, username, password);
        PreparedStatement stmt=connection.prepareStatement(sql);
        stmt.setInt(1,buildingId);
        ResultSet rs=stmt.executeQuery();
        while(rs.next()) {
            String name = rs.getString("name");
            if(name!=null)
                return name;
        }
        return null;
    }

    public  List<Integer> getEmptyBedNumbersByRoomId(Integer roomId) throws ClassNotFoundException, SQLException {
        List< Integer> bedNumbers=new ArrayList<>();
        Class.forName("com.mysql.cj.jdbc.Driver");
        String sql="select bed_number from bed where room_id=? and student_id is null";
        Connection connection= DriverManager.getConnection(url, username, password);
        PreparedStatement stmt=connection.prepareStatement(sql);
        stmt.setInt(1,roomId);
        ResultSet rs=stmt.executeQuery();
        while(rs.next()) {
            bedNumbers.add(rs.getInt("bed_number"));
        }
        return bedNumbers;
    }

    public  void addBedAssignment(Integer bedNumber,Integer roomId,Integer studentId) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        //  获取连接
        String sql="update bed set student_id=? where bed_number=? and room_id=?";
        Connection connection= DriverManager.getConnection(url,username,password);
        //  创建statement
        PreparedStatement stmt=connection.prepareStatement(sql);
        stmt.setInt(1,studentId);
        stmt.setInt(2,bedNumber);
        stmt.setInt(3,roomId);
        int i=stmt.executeUpdate();
        System.out.println("SQL语句执行完毕影响的记录数为"+i);
        stmt.close();
        connection.close();
    }


    public  Integer getBedNumberByStudentId(Integer studentId) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String sql="select bed_number from bed where student_id=?";
        Connection connection= DriverManager.getConnection(url, username, password);
        PreparedStatement stmt=connection.prepareStatement(sql);
        stmt.setInt(1,studentId);
        ResultSet rs=stmt.executeQuery();
        while(rs.next()) {
            int bedNumber=rs.getInt("bed_number");
            return bedNumber;
        }
        return null;
    }
}
